package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojo.WmChannel;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.jcraft.jsch.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;


    @Override
    @Async
    public void autoScanNews(Integer id) {

        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId,id));
        if (wmNews==null){
            throw new RuntimeException("WMnewsAutoScanService----文章不存在");
        }


        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){


            Map<String,Object> map = handleTextAndImages(wmNews);

            boolean isTextScan = handleTextScan((String) map.get("content"),wmNews);
            if (!isTextScan){
                return;
            }

            boolean isImageScan = handleImageScan((List<String>) map.get("image"),wmNews);
            if (!isImageScan){
                return;
            }

            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals("200")){
                throw new RuntimeException("wmNewsAutoScanServiceImpl-文章审核,保存app端文章数据失败");
            }
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");
        }

    }



    private void updateWmNews(WmNews wmNews , short status , String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    private ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();

        BeanUtils.copyProperties(wmNews,dto);

        dto.setLayout(wmNews.getType());

        WmChannel wmChannel = wmChannelMapper.selectOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getId, wmNews.getChannelId()));
        if (wmChannel!=null){
            dto.setChannelName(wmChannel.getName());
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            dto.setAuthorName(wmUser.getName());
        }
        if (wmNews.getArticleId()!=null){
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());


        ResponseResult responseResult = iArticleClient.saveArticle(dto);

        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;
    private boolean handleImageScan(List<String> image, WmNews wmNews) {

        boolean flag = true;
        image = image.stream().distinct().collect(Collectors.toList());

        ArrayList<byte[]> bytes1 = new ArrayList<>();
        for (String s : image) {
            byte[] bytes = fileStorageService.downLoadFile(s);
            bytes1.add(bytes);
        }
        try {
            Map map = greenImageScan.imageScan(bytes1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;

    }

    @Autowired
    private GreenTextScan greenTextScan;
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;
        try {
            Map map = greenTextScan.greeTextScan(content);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return flag;
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
//
//        StringBuilder stringBuilder = new StringBuilder();
//        ArrayList<String> arrayList = new ArrayList<>();
//
//        if (StringUtils.isNotBlank(wmNews.getContent())){
//            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);
//            for (Map map : list) {
//                if (map.get("type").equals("text")){
//
//                    stringBuilder.append(map.get("value"));
//                }
//                if (map.get("type").equals("image")){
//                    arrayList.add((String) map.get("value"));
//                }
//            }
//        }
//
//        if(StringUtils.isNotBlank(wmNews.getImages())){
//            String[] split = wmNews.getImages().split(",");
//            arrayList.addAll(Arrays.asList(split));
//        }
//
//        HashMap<String, Object> hashMap = new HashMap<>();
//        hashMap.put("content",stringBuilder.toString());
//        hashMap.put("image",arrayList);
//        return hashMap;

        StringBuilder stringBuilder = new StringBuilder();

        ArrayList<String> image = new ArrayList<>();

        if (StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : list) {
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                if (map.get("type").equals("image")){
                    image.add((String) map.get("value"));
                }
            }
        }

        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            image.addAll(Arrays.asList(split));
        }

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("text",stringBuilder.toString());
        stringObjectHashMap.put("image",image);
        return stringObjectHashMap;

    }
}
